import { fetchMirrorWebsite } from "@/spider/ipc";
import semver from "semver";

export const mvndMirrors = {
  official: "https://dlcdn.apache.org/maven/mvnd/",
  tsinghua: "https://mirrors.tuna.tsinghua.edu.cn/apache/maven/mvnd/",
  tencent: "https://mirrors.cloud.tencent.com/apache/maven/mvnd/",
  huaweicloud: "https://mirrors.huaweicloud.com/apache/maven/mvnd/",
  aliyun: "https://mirrors.aliyun.com/apache/maven/mvnd/",
};

export async function getMvndVersions(): Promise<string[]> {
  try {
    return await Promise.any([
      getMavenVersions0(mvndMirrors.tsinghua),
      getMavenVersions0(mvndMirrors.tencent),
      getMavenVersions0(mvndMirrors.official),
    ]);
  } catch (e: any) {
    console.log("get maven versions error", e);
    return [];
  }
}

export async function getMvndVersionsViaHuaweiCloud(): Promise<string[]> {
  try {
    return await getMavenVersions0(mvndMirrors.huaweicloud);
  } catch (e: any) {
    console.log("get maven versions error", e);
    return [];
  }
}

async function getMavenVersions0(url: string): Promise<string[]> {
  let versions: string[] | null = null;
  try {
    const resp = await fetchMirrorWebsite(url);
    // 过滤掉 1.0-m6/7/8的版本
    versions = resp.filter(it => /^\d+\..*$/.test(it.name) && !/m\d+$/.test(it.name)).map(it => it.name);
    versions.sort((a, b) => semver.compare(b, a));
  } catch (e: any) {
    console.log("get maven versions error", url, e);
  }
  if (versions != null && versions.length > 0) {
    return versions;
  }
  throw new Error("fetch failed for " + url);
}

export function getMvndFilePlatform() {
  return proc.platform === "win32" ? "windows" : proc.platform;
}

export function getMvndFileArch() {
  if (proc.platform === "darwin" && proc.arch === "arm64") return "aarch64";
  return "amd64";
}

export function getMvndDownloadPath(mirror: string, version: string) {
  return `${mirror}${version}/maven-mvnd-${version}-${getMvndFilePlatform()}-${getMvndFileArch()}.zip`;
}

export function getMvndFileName(version: string, ext = "zip") {
  return `maven-mvnd-${version}-${getMvndFilePlatform()}-${getMvndFileArch()}.${ext}`;
}
